using MassTransit;
using FServer.Core.Interfaces;

namespace FServer.Infrastructure.Services;

public class RabbitMQService : IMessageQueueService
{
    private readonly IBus _bus;
    private readonly ILogger<RabbitMQService> _logger;

    public RabbitMQService(IBus bus, ILogger<RabbitMQService> logger)
    {
        _bus = bus;
        _logger = logger;
    }

    public async Task PublishAsync<T>(T message, string? routingKey = null)
    {
        try
        {
            await _bus.Publish(message);
            _logger.LogDebug("Published message of type {MessageType}", typeof(T).Name);
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "Failed to publish message of type {MessageType}", typeof(T).Name);
            throw;
        }
    }

    public async Task SubscribeAsync<T>(string queueName, Func<T, Task> handler)
    {
        // 这里需要实现订阅逻辑
        // 在实际实现中，这通常通过 MassTransit 的消费者配置来完成
        await Task.CompletedTask;
    }

    public async Task StartAsync()
    {
        try
        {
            await _bus.StartAsync();
            _logger.LogInformation("RabbitMQ service started");
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "Failed to start RabbitMQ service");
            throw;
        }
    }

    public async Task StopAsync()
    {
        try
        {
            await _bus.StopAsync();
            _logger.LogInformation("RabbitMQ service stopped");
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "Failed to stop RabbitMQ service");
            throw;
        }
    }
}
